<?php
/* 
* @Author: LDF QQ 47121862
* @Date:   2014-05-17 16:08:42
* @Last Modified by:   LDF QQ 47121862
* @Last Modified time: 2014-05-27 14:58:28
*/
class goodsModel extends viewModel{
	public $table = 'Goods';
	public $pics; //内容页上传图片
	public $view = array(
		'category' => array(
			'type' => INNER_JOIN,
			'on' => 'goods.cid=category.cid'
		)
	);
	public $validate=array(
		array('gname','nonull','商品名称不能为空',2,3),
		array('cid','nonull','请选择栏目',2,3),
		// array('bid','nonull','请选择品牌',2,3),
		// array('spec[stock]','nonull','库存不能为空',2,3),
		// array('spec[price]','nonull','价格不能为空',2,3),
		// array('spec[goods_sn]','nonull','货号不能为空',2,3)
	);
	public $auto=array(
		array('addtime','strtotime','function',1,3),
		array('flag','cFlag','method',1,3),
		array('index_pic','cIndexPic','method',2,3),
		array('list_pic','cListPic','method',2,3)
		// array('pic','cPic','method',2,3)
	);
	public function cFlag($flag){
		return implode(',', $flag);
	}
	public function cIndexPic($pic){
		if(!empty($_FILES['index_pic']['name'])){
			if(isset($_POST['indexPic'])) @unlink($_POST['indexPic']);
			$u = new Upload();
			$info = $u->upload('index_pic');
			return $info[0]['path'];
		}
	}
	public function cListPic($pic){
		if(!empty($_FILES['list_pic']['name'])){
			if(isset($_POST['listPic'])) @unlink($_POST['listPic']);
			$u = new Upload();
			$info = $u->upload('list_pic');
			return $info[0]['path'];
		}
	}
	//内容页图处理
	// public function cPic($pic){
	// 	if(!empty($_FILES['pic']['name'])){
	// 		if(isset($_POST['pic'])) @unlink($_POST['pic']);
	// 		$u = new Upload();
	// 		$info = $u->upload('pic');
	// 		// return $info;
	// 	}
	// }
	//添加商品
	public function addGoods(){
		if($this->create()){
			$this->cPic();
			$gid = $this->add();
			if($gid){
				$this->addContPic($gid); //添加内容页图片
				$this->addGoodsAttr($gid); //添加商品属性
				$this->addStock($gid); //添加库存
				return $gid;
			}else{
				$this->error='添加商品失败';
				return false;
			}
			return false;
		}
	}
	//添加库存
	public function addStock($gid,$s=null){
		$db=M('stock');
		$saDb=M('stock_attr');
		//第二个参数为编辑，先清空后插入数据
		$db->where('gid='.$gid)->del();
		if($s){
			$saDb->where('gid='.$gid)->del();
		}
		$specData['gid']=$gid;
		$spec = isset($_POST['spec'])?$_POST['spec']:false;
		//组合库存表数据
		if($spec){
			foreach($spec['stock'] as $k => $v){
				if(isset($spec['stid'][$k])){
					$specData['stid']=$spec['stid'][$k];
				}else{
					$specData['stid']=null;
				}
				$specData['stock'] = $spec['stock'][$k];
				$specData['price'] = $spec['price'][$k];
				$specData['goods_sn'] = $spec['goods_sn'][$k];
				//写入库存表
				// p($specData);
				$stid = $db->add($specData);
				if($stid){
					//组合库存值表数据
					$cid = Q('cid',0,'intval');
					// $total = count($spec['stock']);
					foreach ($spec['attr'] as $key => $value) {
						// $info = explode('|', $spec['attr'][$key][$k]);
						$info = explode('|', $value[$k]);
						$stData['stid']=$stid;
						$stData['gid']=$gid;
						$stData['cid']=$cid;
						$stData['avid']=$info[0];
						//写入库存值表
						$saDb->add($stData);
					}	
				}
			}
			//组合商品属性表数据
			foreach ($spec['attr'] as $v) {
				foreach ($v as $key => $value) {
					//去除重复
					$info = explode('|', $value);
					$attr[$info[0]]=$value;
				}
			}
			//同时将规格写入商品属性表
			$this->addGoodsAttr($gid,$attr);
		}else{
			//没有规格情况下写入库存表
			$storckData['gid'] = $gid;
			$storckData['stock'] = $_POST['stock'];
			$storckData['price'] = $_POST['price'];
			$storckData['goods_sn'] = $_POST['goods_sn'];
			$db->add($storckData);
		}
		//修改原商品的价格与库存
		$data['price'] = M('stock')->where("gid=$gid")->order('price ASC')->getField('price');
		$data['stock'] = M('stock')->where("gid=$gid")->sum('stock');
		M('goods')->where("gid=$gid")->save($data);
	}
	//添加商品属性
	private function addGoodsAttr($gid,$attrValue=null){
		$db = M('goods_attr');
		is_null($attrValue)?$attr=$_POST['attr']:$attr=$attrValue;
		$cid = Q('cid',0,'intval');
		foreach ($attr as $k => $v) {
			$data['cid']=$cid;
			$data['gid']=$gid;
			//组合input,textarea
			if(strchr($k,'|')){
				$info = explode('|',$k);
				$data['avid']=$info[1];
				$data['avalue']=$v;
			}else{
				//组合select,radio,checkbox
				$info = explode('|',$v);
				$data['avid']=$info[0];
				$data['avalue']=$info[1];
			}
			$db->add($data);
		}
	}
	//修改商品
	public function editGoods(){
		if($this->create()){
			//防止修改时候没有选择上传图片
			if(empty($this->data['index_pic'])) unset($this->data['index_pic']);
			if(empty($this->data['list_pic'])) unset($this->data['list_pic']);
			$id = $this->save();
			$gid = Q('gid',0,'intval');
			$this->cPic(); //上传图片
			if($id){
				$this->addContPic($gid); //添加内容页图片
				//删除商品属性
				M('goods_attr')->where('gid='.$gid)->del();
				$this->addGoodsAttr($gid); //添加商品属性
				//删除库存
				// M('stock_attr')->where('gid='.$gid)->del();
				$this->addStock($gid,1); //添加库存
				return $id;
			}else{
				$this->error='修改商品失败';
				return false;
			}
			return false;
		}
	}
	//删除商品
	public function delGoods(){
		$gid = Q('gid',0,'intval');
		$data = $this->find($gid);
		$picDb = M('goods_pic');//图片
		$pics = $picDb->where('gid='.$gid)->all();
		//删除主页图和列表页图
		if($data['index_pic'])
			@unlink(ROOT_PATH.$data['index_pic']);
		if($data['list_pic'])
			@unlink(ROOT_PATH.$data['list_pic']);
		//删除内容页图片
		if($pics){
			foreach ($pics as $p) {
				@unlink(ROOT_PATH.$p['small']);
				@unlink(ROOT_PATH.$p['medium']);
				@unlink(ROOT_PATH.$p['big']);
			}
		}
		$picDb->where('gid='.$gid)->del(); //删除图片表
		M('goods_attr')->where('gid='.$gid)->del(); //删除商品属性表
		M('stock')->where('gid='.$gid)->del(); //删除商品库存表
		M('stock_attr')->where('gid='.$gid)->del(); //删除库存属性表
		return $this->del($gid); //删除商品
	}
	//内容页图处理，删除旧图片，上传新图片
	private function cPic(){
		if(!empty($_FILES['pic']['name'])){
			if(isset($_POST['pic'])) @unlink($_POST['pic']);
			$u = new Upload();
			$info = $u->upload('pic');
			$this->pics = $info;
		}
	}
	//添加内容页图片，生成缩略图，并删除原图片
	private function addContPic($gid){
		if($this->pics){
			$pd = M('goods_pic');
			$i = new Image();
			foreach ($this->pics as $v) {
				$big = $v['dir'].$v['filename'].'_800x800.'.$v['ext'];
				$medium = $v['dir'].$v['filename'].'_350x350.'.$v['ext'];
				$small = $v['dir'].$v['filename'].'_50x50.'.$v['ext'];
				$i->thumb($v['path'],$big,800,800);
				$i->thumb($v['path'],$medium,350,350);
				$i->thumb($v['path'],$small,50,50);
				@unlink(ROOT_PATH.$v['path']);
				$pd->add(array('big'=>$big,'small'=>$small,'medium'=>$medium,'gid'=>$gid));
			}
		}
	}
	//更新缓存
	public function updateCache(){
		$goods = $this->order('cid DESC')->getField('gid,gname,price,stock,hd_g_goods.keywords,hd_g_goods.description,body,service,click,addtime,flag,pic,index_pic,list_pic,uid,bid,hd_g_goods.cid,cname,unit,price_ange');
		return cache('goodsCache',$goods);
	}
}
